
import qs from 'qs'
export function getCookie(name, isObject) {
    let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr === document.cookie.match(reg)) {
        let parse = arr[2]

        if (isObject) {
            try {
                //替换'为",用于unescape解析 然后使用qs解析转译的'
                //解析成功则该值为object，返回该对象
                parse = qs.parse((unescape(parse).replace(/'/g, '"')))
            }
            catch {
                console.log('用于unescape解析失败')
            }
        }
        return parse;
    }

    else
        return null;
}

//设置cookie,增加到vue实例方便全局调用
export function setCookie(c_name, value, expiredays) {
    if (typeof (value) === 'object') {
        //qs将'转译,替换"为'用于后续escape存储（escape不识别"）
        value = qs.stringify(value).replace(/"/g, "'")
    }
    console.log('setCookie:' + c_name)
    let exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
};

//删除cookie
export function delCookie(name) {
    console.log('delCookie:' + name)
    let exp = new Date();
    exp.setTime(exp.getTime() - 1);
    let cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
};
